package net.qhzw.vip.qiyu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.dto.DeliveryResultDto;
import net.qhzw.vip.qiyu.dto.ShipTraceDto;
import net.qhzw.vip.qiyu.entity.Delivery;
import net.qhzw.vip.qiyu.entity.Order;
import net.qhzw.vip.qiyu.handler.ApiException;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.DeliveryService;
import net.qhzw.vip.qiyu.service.OrderService;
import net.qhzw.vip.qiyu.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class DeliveryController {

    @Autowired
    private DeliveryService deliveryService;

    @Autowired
    private OrderService orderService;

    @Value("${alicloud.app-code}")
    private String appCode;

    /**
     * 分页获取
     */
    @GetMapping("/admin/delivery/list")
    public JsonResult<List<Delivery>> page() {
        List<Delivery> list = deliveryService.list();
        return JsonResult.ok(list);
    }

    /**
     * 查看物流接口
     */
    @GetMapping("/delivery/check")
    @ApiOperation(value = "查看物流", notes = "根据订单号查看物流")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public JsonResult<DeliveryResultDto> checkDelivery(String orderNumber) {
        Order order = orderService.getOrderByOrderNumber(orderNumber);
        Delivery delivery = deliveryService.getById(order.getDvyId());
        DeliveryResultDto deliveryDto = getDeliveryDto(delivery.getDvyType(), order.getDvyFlowId());
        return JsonResult.ok(deliveryDto);
    }
    private DeliveryResultDto getDeliveryDto(String shipCode, String shipNo) {
        ShipTraceDto shipTrace = new ShipTraceDto();
        try {
            String orderTracesByJson = getOrderTracesByJson(shipCode, shipNo);
            if (!StringUtils.isEmpty(orderTracesByJson)) {
                shipTrace = JSONObject.parseObject(orderTracesByJson, ShipTraceDto.class);
            }
            if ("ok".equals(shipTrace.getMsg())) {
                DeliveryResultDto result = shipTrace.getResult();
                return result;
            }
        } catch (Exception e) {
            log.error("[快递鸟 查询] 异常", e);
        }
        return null;
    }

    /**
     * Json方式 查询订单物流轨迹
     * @throws Exception
     */
    private String getOrderTracesByJson(String shipCode, String shipNo) {
        log.info("快递公司识别编码 : {}, 订单号为: {}", shipCode, shipNo);
        String host = "https://kdwlcxf.market.alicloudapi.com";
        String path = "/kdwlcx";
        String method = "GET";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, String> querys = new HashMap<>();
        querys.put("no", shipNo.trim());
        querys.put("type", shipCode);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            //获取response的body
            String ss = EntityUtils.toString(response.getEntity());
            log.info("查询到的数据为: {}", ss);
            if (StringUtils.isEmpty(ss)){
                throw new ApiException("查询订单物流轨迹异常");
            }
            JSONObject jsonObject = JSONObject.parseObject(ss);
            return JSON.toJSONString(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        }
    }




}
